<template>
  <a-form
    class="register-form"
    ref="formRef"
    layout="horizontal"
    :rules="rules"
    :model="formState"
    :wrapper-col="wrapperCol"
  >
    <a-form-item name="username">
      <a-input
        autofocus
        v-model:value="formState.username"
        placeholder="用户名"
      >
        <template #prefix
          ><UserOutlined style="color: rgba(0, 0, 0, 0.25)"
        /></template>
      </a-input>
    </a-form-item>
    <a-form-item name="password">
      <a-input-password
        v-model:value="formState.password"
        type="password"
        placeholder="密码"
      >
        <template #prefix
          ><LockOutlined style="color: rgba(0, 0, 0, 0.25)"
        /></template>
      </a-input-password>
    </a-form-item>
    <a-form-item>
      <a-button
        type="primary"
        @click="onSubmit"
        style="width: 100%"
        :disabled="formState.username === '' || formState.password === ''"
      >
        注册
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRaw, UnwrapRef } from "vue";
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue";
import { RegisterForm } from "model";
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import { register } from "@/controller/User";
import { useRouter } from "vue-router";
import message from "ant-design-vue/es/message";

export default defineComponent({
  name: "RegisterForm",
  components: {
    UserOutlined,
    LockOutlined,
  },
  setup() {
    const formRef = ref();
    const router = useRouter();
    const formState: UnwrapRef<RegisterForm> = reactive({
      username: "",
      password: "",
    });
    const onSubmit = () => {
      formRef.value
        .validate()
        .then(async () => {
          try {
            await register(toRaw(formState));
            message.success(formState.username + "注册成功");
            router.push({
              name: "Login",
            });
          } catch (e) {
            message.error("注册失败" + e);
          }
        })
        .catch((error: ValidateErrorEntity<RegisterForm>) => {
          message.error("登录格式错误，请输入完整后登录");
          console.log(error);
        });
    };
    const rules = {
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        {
          min: 2,
          max: 5,
          message: "用户名长度在2到5个字符之前",
          trigger: ["change", "blur"],
        },
      ],
      password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        {
          min: 3,
          max: 15,
          message: "密码需在3到15个字符之间",
          trigger: ["change", "blur"],
        },
      ],
    };
    return {
      formRef,
      formState,
      wrapperCol: { span: 24 },
      rules,
      onSubmit,
    };
  },
});
</script>

<style scoped lang="scss"></style>
